package member

import (
	"encoding/json"

	"fmt"

	"net/http"

	"awfan.cn/implement/school"
	"awfan.cn/utils"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

func create(format string, body []byte, w http.ResponseWriter, db *mgo.Database) {
	data := MEMBER_XML{}

	err := json.Unmarshal(body, &data)

	if err != nil {
		utils.WriteError(format, 404, err.Error(), w)
		return
	}

	if data.Name == "" {
		utils.WriteError(format, 404, "#name is empty", w)
		return
	}

	if data.Password == "" {
		utils.WriteError(format, 404, "#password is empty", w)
		return
	}

	if !bson.IsObjectIdHex(data.School.Id) {
		utils.WriteError(format, 404, fmt.Sprintf("#school id is wrong format:'%v'", data.School), w)
		return
	}

	c1 := db.C(utils.PkgName(school.SCHOOLS_XML{}))

	count, err := c1.FindId(bson.ObjectIdHex(data.School.Id)).Count()

	if err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}

	if count <= 0 {
		utils.WriteError(format, 401, fmt.Sprintf("#school not exist with id '%v'", data.School), w)
		return
	}

	c2 := db.C(utils.PkgName(MEMBER_XML{}))

	count, err = c2.Find(bson.M{"name": bson.RegEx{"^" + data.Name + "$", "i"}, "school": data.School}).Count()

	if err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}

	if count > 0 {
		utils.WriteError(format, 402, fmt.Sprintf("#name exist  '%v'", data.Name), w)
		return
	}

	data.Id = bson.NewObjectId()
	data.Created_time = bson.Now()

	err = c2.Insert(&data)

	if err != nil {
		utils.WriteError(format, 404, err.Error(), w)
		return
	}

	utils.WriteEmpty(format, w)
}
